package com.example.anew.journey.mynewjourney.base;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.constraint.Guideline;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.anew.journey.mynewjourney.R;
import com.example.anew.journey.mynewjourney.config.RBConstants;
import com.example.anew.journey.mynewjourney.firstchangelogic.FirstChangeMain.FirstChangeMainActivity;
import com.example.anew.journey.mynewjourney.logic.login.bean.LoginBean;
import com.example.anew.journey.mynewjourney.logic.thirdPartyLogin.ThirdPartyLoginActivity;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jesse.nativelogger.NLogger;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 杭州惟君医疗科技有限公司14
 * Created by 20433 on 2018/3/6
 */

public abstract class BasePasswordFreeLoginAndRegisteredActivity extends BaseRegisteredAndLoginActivity {
    @Bind(R.id.activity_registered_or_login_tv_dec)
    TextView activityRegisteredOrLoginTvDec;
    @Bind(R.id.activity_registered_or_login_iv_phone)
    ImageView activityRegisteredOrLoginIvPhone;
    @Bind(R.id.activity_registered_or_login_et_phone_number)
    EditText activityRegisteredOrLoginEtPhoneNumber;
    @Bind(R.id.linearLayout2)
    LinearLayout linearLayout2;
    @Bind(R.id.activity_registered_or_login_bt_get_version_code)
    Button activityRegisteredOrLoginBtGetVersionCode;
    @Bind(R.id.activity_registered_or_login_tv_other)
    TextView activityRegisteredOrLoginTvOther;
    @Bind(R.id.textView3)
    TextView textView3;
    @Bind(R.id.guideline)
    Guideline guideline;
    @Bind(R.id.activity_registered_or_login_iv_qq)
    ImageView activityRegisteredOrLoginIvQq;
    @Bind(R.id.activity_registered_or_login_iv_wechat)
    ImageView activityRegisteredOrLoginIvWechat;
    @Bind(R.id.activity_registered_or_login_tv_agreement)
    TextView ctivityRegisteredOrLoginTvAgreement;


    protected PlatformActionListener paListener;
    public int MY_PAGE_INTEGRATAION_CODE = 0;

    private static final int MSG_TOAST = 1;
    private static final int MSG_ACTION_CCALLBACK = 2;
    private static final int MSG_CANCEL_NOTIFY = 3;

    public String third_party_login_id;
    public String third_party_login_name;
    public String third_party_login_state;
    /** QQ好友分享对象 */
    private Platform platform_qqFriend;
    @Override
    protected void initView(View view) {
// todo Toolbar的一系列操作
        setToolbarBg(0xffffffff);
        displayBtRelease();
        setBtReleaseBg(0XFFFFFFFF);
        setBtRelease("密码登录", 18, 0xff666666);
        hiddenReturn();
        initDate();

        Intent intent = getIntent();
        third_party_login_id = intent.getStringExtra("third_party_login_id");
        third_party_login_name = intent.getStringExtra("third_party_login_name");
        third_party_login_state = intent.getStringExtra("third_party_login_state");
        MY_PAGE_INTEGRATAION_CODE = intent.getIntExtra("my_page_integration_code",0);
        NLogger.e("TAG","========456========"+MY_PAGE_INTEGRATAION_CODE);
    }

    @Override
    protected View setMainContentView() {
        View view = View.inflate(this, R.layout.activity_registered_or_login, null);
        ButterKnife.bind(this,view);
        return view;
    }

    @OnClick({R.id.activity_registered_or_login_bt_get_version_code, R.id.activity_registered_or_login_tv_other, R.id.activity_registered_or_login_iv_qq, R.id.activity_registered_or_login_iv_wechat})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_registered_or_login_bt_get_version_code: //手机号
                //if (util.check()) return;
                String phoneNumber = activityRegisteredOrLoginEtPhoneNumber.getText().toString().trim();
                erificationvMobile(phoneNumber);
                break;
            case R.id.activity_registered_or_login_tv_other:
                //if (util.check()) return;
                tvOther();
                break;
            case R.id.activity_registered_or_login_iv_qq: //微信
              //  if (util.check()) return;
                onClickWecht();
                NLogger.e("TAG","========微信==开始======");
                break;
            case R.id.activity_registered_or_login_iv_wechat: //qq
                //if (util.check()) return;
                onClickQQ();
                break;
        }
    }

    public   void erificationvMobile(String phoneNumber) {
       // String regex = "^((13[0-9])|(14[0-9])|(15([0-9]))|(17[0-9])|(18[0-9]))\\d{8}$";
        String regex = "^((1[0-9][0-9]))\\d{8}$";
        if (phoneNumber.length() != 11) {
           // System.out.println("手机号应为11位数");
            Toast.makeText(this,"手机号应为11位数",Toast.LENGTH_SHORT).show();
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phoneNumber);
            boolean isMatch = m.matches();
            if (isMatch) {
                toGetVersionCode(phoneNumber);
            } else {
               // System.out.println("您的手机号" + phoneNumber + "格式错误");
                Toast.makeText(this,"手机号格式错误",Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * @desc 其他
     * */
    protected  void tvOther(){

    }

    /**
     * @desc 第三方微信登陆
     * */
    protected  void wechatLogin(){
       // showShare();
    }

    /**
     * @desc 第三方QQ登陆
     * */
    protected  void qqLogin(){
        //showShareQQ();
    }
    /**
     * @desc 根据获取到的手机号跳转到获取验证码页面
     * */
    protected abstract void toGetVersionCode(String trim);

    /**
     * @desc 隐藏底部协议
     * */
    protected void  hiddenTvAgreement(){
        ctivityRegisteredOrLoginTvAgreement.setVisibility(View.GONE);
    }
    /**
     * @desc 显示底部协议
     * */
    protected void displayTvAgreement(){
        ctivityRegisteredOrLoginTvAgreement.setVisibility(View.VISIBLE);
    }
    /**
     * @desc 初始化数据
     * */
    protected abstract void initDate();
    /**
     * @desc Activity 销毁 释放资源
     */
    @Override
    protected void releaseResources() {
        ButterKnife.unbind(this);
    }

    //点击微信登陆
    public void onClickWecht() {
        Platform Wachzone = ShareSDK.getPlatform(Wechat.NAME);
        if(Wachzone.isAuthValid()) {
            Wachzone.removeAccount(true);
        }
        Wachzone.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub
                arg2.printStackTrace();
               // NLogger.e("TAG","=====微信===登录失败========"+ arg2);
                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(BasePasswordFreeLoginAndRegisteredActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                });

            }
            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                // TODO Auto-generated method stub
                //输出所有授权信息
                arg0.getDb().exportData();
                //获取资料
                String UserName = arg0.getDb().getUserName();//获取用户名字
                String Icon = arg0.getDb().getUserIcon(); //获取用户头像
                String token = arg0.getDb().getToken();
                String userId =  arg0.getDb().getUserId();
                LoginWecht("weixin",userId);

            }
            @Override
            public void onCancel(Platform arg0, int arg1) {
               // NLogger.e("TAG","=====微信===登录取消========");
                // TODO Auto-generated method stub
                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(BasePasswordFreeLoginAndRegisteredActivity.this, "登录取消", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
//authorize与showUser单独调用一个即可
        Wachzone.authorize();//单独授权，OnComplete返回的hashmap是空的
    }
    // 点击qq登陆
    public void onClickQQ() {
        Platform qzone = ShareSDK.getPlatform(QQ.NAME);
        if(qzone.isAuthValid()) {
            qzone.removeAccount(true);
        }
        qzone.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub
                arg2.printStackTrace();
                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(BasePasswordFreeLoginAndRegisteredActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                // TODO Auto-generated method stub
                //输出所有授权信息
                arg0.getDb().exportData();
                //获取资料
                String UserName = arg0.getDb().getUserName();//获取用户名字
                String Icon = arg0.getDb().getUserIcon(); //获取用户头像
                String token = arg0.getDb().getToken();
                String userID =  arg0.getDb().getUserId();
                LoginWecht("qq",userID);
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub
                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(BasePasswordFreeLoginAndRegisteredActivity.this, "登录取消", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        qzone.authorize();//单独授权，OnComplete返回的hashmap是空的
    }
    private void LoginWecht(final String weixin, final String userId) {
        String url = RBConstants.SERVER_URL+RBConstants.THIRD_PARTY_LOGIN;
        NLogger.e("TAG","=====23=12===weixin============"+weixin);
        NLogger.e("TAG","=====23=12===userId============"+userId);
        NLogger.e("TAG","=====23=12===url============"+url);
        OkHttpUtils
                .post()
                .url(url)
                .addParams(weixin,userId)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson = new Gson();
                        NLogger.e("TAG","=====23=12===LoginWecht============"+NetworkResponseDate);
                        final LoginBean bean =  gson.fromJson(NetworkResponseDate, LoginBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(bean.errorCode == 200){
                                    Intent intent_01 = new Intent(BasePasswordFreeLoginAndRegisteredActivity.this, FirstChangeMainActivity.class);
                                    intent_01.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(intent_01);
                                    finish();
                                    LoginBean.DataBean mbean = bean.data;
                                    //todo 存储
                                    if(bean != null) {
                                        //获取一个文件名为test、权限为private的xml文件的SharedPreferences对象
                                        SharedPreferences sharedPreferences = getSharedPreferences("My_App_Cardiac", MODE_PRIVATE);
                                        //得到SharedPreferences.Editor对象，并保存数据到该对象中
                                        SharedPreferences.Editor editor = sharedPreferences.edit();
                                        editor.putString("my_use_id", mbean.id);
                                        editor.putString("my_use_name", mbean.cus_name);
                                        editor.putString("my_use_tel", mbean.tel);
                                        editor.putString("my_use_logo", mbean.cus_logo);
                                        editor.putString("my_use_birthday", mbean.birthday);
                                        editor.putString("my_use_state", mbean.state);
                                        editor.putString("my_use_qq", mbean.qq);
                                        editor.putString("my_use_weixin", mbean.weixin);
                                        editor.putString("my_use_token", mbean.token);
                                        editor.putBoolean("my_is_login",true);
                                        editor.putInt("my_stored_data_number",0);
                                        //保存key-value对到文件中
                                        editor.commit();
                                        toMainPager();

                                    }
                                    Toast.makeText(BasePasswordFreeLoginAndRegisteredActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                                }else if(bean.errorCode == 4001){  //未绑定手机号
                                    Intent intent = new Intent(BasePasswordFreeLoginAndRegisteredActivity.this,ThirdPartyLoginActivity.class);
                                    intent.putExtra("third_party_login_state","1");  //Third party login
                                    NLogger.e("TAG","=========state=====rey===userId===="+userId);
                                    NLogger.e("TAG","=========state=====rey===weixin===="+weixin);
                                    intent.putExtra("third_party_login_id",userId);  //Third party login
                                    intent.putExtra("third_party_login_name",weixin);  //Third party login
                                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                                    startActivity(intent);

                                    Toast.makeText(BasePasswordFreeLoginAndRegisteredActivity.this,"未绑定手机号，请注册手机号",Toast.LENGTH_SHORT).show();
                                }
                            }
                        });


                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        NLogger.e("TAG","=========state====123=rey======="+e);
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }

    protected abstract void toMainPager();


}
